const fs = require("fs");
const co = require("co");
var path = require("path");
var photo_dir = "/photos"
var exec = require('child_process').exec;
var ossup = require("./aliyun/oss");
var ipchandle = require("./ipchandle");
var magick = require("imagemagick");


/**
 * 打开相册目录
 */
ipchandle.on('opendir', (data,res) => {

    var opendir = path.join(photo_dir,data.path,"original");

    if(data.finish){
        opendir = path.join(photo_dir,data.path,"photos");
    }else{
        util.mk_dir(photo_dir,data.path+"/original");
        util.mk_dir(photo_dir,data.path+"/compress");
        util.mk_dir(photo_dir,data.path+"/select");
        util.mk_dir(photo_dir,data.path+"/photos");
    }

    //console.log('Explorer '+path.join(photo_dir,arg));
    exec('Explorer '+opendir, function(err, stdout, stderr) {
        if (err) {
            console.dir(err);
            res.end({
                code:-1,
                message:"err"
            });
        }else{
            res.end({
                code:1,
                message:"ok"
            });
        }

    });
});


/**
 * 打包文件
 */
ipchandle.on('package', (data,res) => {


    var filefinish = path.join(photo_dir,data.path,"photos");
    var filedir = path.join(photo_dir,data.path,data.applyid+".rar");

    exec('rar a '+filedir+" -ep1 "+filefinish, function(err, stdout, stderr){
        if (err) {
            console.dir(err);
            res.end({
                code:-1,
                message:"err"
            });
        }else{

            var up_path = data.path+"/"+data.applyid+".rar"
            co(function*(){
                var rs = yield ossup.putProgress(up_path,filedir,function(p,cpt){
                    //console.log(p);
                    res.reply({
                        code:1,
                        progress:parseInt(p*100),
                        total:100
                    });
                });

                //console.log(rs);
                /*
                callback({
                    code:0,
                    upload:rs.url
                });
                */
                console.log("upload: ",rs.url);
                res.end({
                    code:1,
                    upload:rs.url,
                    message:"ok"
                });


                //console.log("upload: ",rs.name);
            });


        }

        console.log("package file:"+filedir);
    });
});

/**
 * 导出用户选片
 */
ipchandle.on('copyfiles', (data,res) => {
    /*
    console.log(facephoto);

    var facephoto = JSON.parse(data.choosen.facephoto);
    var selected = JSON.parse(data.choosen.selected);
    */

    
    var all = JSON.parse(data.choosen.all);
    var product = JSON.parse(data.choosen.product);
    //console.log(product);
    var pdetail = JSON.parse(product.photodetail);
    console.log(data.choosen.choosenmap);

    
    try{
        var choosenmap = JSON.parse(data.choosen.choosenmap);
    }catch(e){
        //console.log(data.choosen);
        var choosenmap = {};
    }
    
    var packall = product.amount == 999;

    var allchs = "";
    //console.log(choosenmap);
    pdetail.forEach(function(detail){
        //console.log(detail.no);
        allchs += ";"+choosenmap[detail.no] || "";
        //console.log(choosenmap[detail.no]);
        var flist = choosenmap[detail.no]?choosenmap[detail.no].split(";"):[];
        //console.log(flist);
        var dirn = detail.name.replace(/\+/g,"_");
        util.mk_dir(path.join(photo_dir,data.path,"select"),dirn);
        flist.forEach(function(filename){
            copy_file(dirn,filename); 
        });
        
    });

    //console.log(allchs);

    //var otherlist;
    if(packall){
        util.mk_dir(path.join(photo_dir,data.path,"select"),"其他底片");
        for(var i=0;i<all.length;i++){
            if(allchs.indexOf(all[i].name)==-1){
                copy_file("其他底片",all[i].name);
            }
        }
    }

    function copy_file(dir,filename){
        var filefrom = path.join(photo_dir,data.path,"original",filename);
        var fileto = path.join(photo_dir,data.path,"select",dir,filename);
        if(!fileto){
            return ;
        }

        exec('copy '+filefrom+" "+fileto,function(err, stdout, stderr){
            if (err) {
                console.dir(err);
            }
            console.log("copy file:"+fileto);
        });        
    }

    exec('Explorer '+path.join(photo_dir,data.path,"select"), function(err, stdout, stderr) {
        if (err) {
            console.dir(err);
            res.end({
                code:-1,
                message:"err"
            });
        }else{
            res.end({
                code:1,
                message:"ok"
            });
        }

    });
});



/**
 * 压缩上传照片
 */
ipchandle.on('compress', (data, res) => {

    fs.readdir(path.join(photo_dir,data.path,"original"),function(err,files){

        //console.log(files.length);
        if(err || !files.length){
            res.end({
                code:-1,
                message:"请先上传图片！"
            });
            return ;
        }


        var total = files.length;
        var progress = 0;

        util.sq(files,function(file,next){
            if(!file) return ;

            setTimeout(next,util.interval);

            util.convert_img(data.path,file,function(rs){
                rs.total = total;
                rs.progress = ++progress;
                res.reply(rs);

                if(rs.progress == total){
					var fileobjs = [];
					files.forEach(function(f){
						fileobjs.push({
							name:f
						});
					});
                    res.end({
                        code:1,
                        number:files.length,
                        images:JSON.stringify(fileobjs)
                    });
                }
            });
        })
    });

})


var util = {
    interval:600,
    mk_dir : function(root,path){
        if(!path)return;

        path = path.replace(/\\/g,"/");
        var dirs = path.split("/");

        var tpath = root;
        while(tpath && dirs.length >0){
            tpath = tpath + "/" + dirs.shift();
            if(!fs.existsSync(tpath)){
                fs.mkdirSync(tpath);
            }
        }
    },

    sq : function(arrs,callback){
        var index = -1;
        function next(){
            index++;
            callback(arrs[index],next);
        }
        setTimeout(next,util.interval);
    },

    convert_img : function(dir,img,callback){

        //console.log(dir);

        var picpath = path.join(photo_dir,dir,"original",img);
        var destpath = path.join(photo_dir,dir,"compress",img);

        var shuiyin_path = path.join(__dirname,"shuiyin4.png");

        /*
        var cmds = ["magick identify -verbose",picpath];

        exec(cmds.join(" "), function(err1, stdout, stderr) {
            console.log(stdout.match(/exif:Orientation:\s*\d+/i)[0]);
            //console.log(stdout);
        })
        */

        /*
        magick.readMetadata(picpath, function(err, metadata){
            if (err) console.dir(err);
            console.log(new Date());
            console.log(picpath);
            console.log('Shot at '+metadata.exif.dateTimeOriginal);            
            callback({
                code:0,
                upload:""
            });
        })
        */

       // return ;

        var cmdx = ["magick", picpath,"-auto-orient","-resize 450","-quality 80", destpath];

        /*
        var cmdx = ["magick", picpath, "-resize 450","-quality 70","-compose over", shuiyin_path,
            "-gravity northwest", "-geometry +10+5","-composite",destpath];
        */

        exec(cmdx.join(" "), function(err1, stdout, stderr) {

            if(err1){
                console.dir(err1);
            }else{
                console.log("mogrify image "+picpath);
            }

            var up_path = path.join(dir,img).replace(/\\/g,"/");

            //fs.writeFileSync("info.log",up_path);

            //console.log("uploading: ",up_path);

            co(function*(){
                var rs = yield ossup.put(up_path,destpath);
                callback({
                    code:0,
                    upload:rs.url
                });
                console.log("upload: ",rs.url);
                //console.log("upload: ",rs.name);
            });

        });
    }
}
